<?php

use console\db\Migration;
use yii\helpers\Json;
use yii\db\Query;

/**
 * 追加原帖子内容中有图片的至图库表
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class m300020_000005_t_sns_dynamic_gallery_format extends Migration {

    /**
     * @inheritdoc
     */
    public $tableName = '{{%sns_dynamic}}';

    /**
     * @inheritdoc
     */
    public function safeUp() {
        $query = (new Query())->from('{{%sns_dynamic_content}}')->select([
            'dynamic_id',
            'attachs'
        ])->where([
            'IS NOT', 'attachs', null
        ])->orderBy([
            'id' => SORT_ASC
        ]);
        $this->handleProgress($query, [$this, 'evenDule']);
    }

    /**
     * @inheritdoc
     */
    public function filterData(&$data) {
        if (!parent::validateTransfer($data)) {
            return false;
        }
        $attachs = Json::decode($data['attachs']);
        if (empty($attachs)) {
            return false;
        }
        $data['attachs'] = $attachs;
        return true;
    }

    /**
     * 处理结果
     * @param Migration $migration
     * @param array $rows
     */
    public static function evenDule($migration, $rows) {
        $connect = $migration->db->createCommand();
        $items = [];
        foreach ($rows as $row) {
            if (!$migration->filterData($row)) {
                continue;
            }
            foreach ($row['attachs'] as $attach) {
                $path = parse_url($attach);
                if (isset($path['host']) && $path['host'] == 'img.lnts.cn' && isset($path['path'])) {
                    $attach = $path['path'];
                }
                if ($attach && strpos($attach, 'http') === false) {
                    $attach = '/uploads/' . ltrim($attach, '/');
                }
                $items[] = [
                    'dynamic_id' => $row['dynamic_id'],
                    'original' => $attach,
                ];
            }
        }
        if (empty($items)) {
            return;
        }
        $connect->batchInsert('{{%sns_dynamic_gallery}}', [
            'dynamic_id',
            'original',
        ], $items)->execute();
    }

}
